
$(function(){
    var reloadTime = 3000; 
    var reloadMessage = 2000;
    var status=[], localStatus=[], localUser = {}, userlist=[], friendsRequests=[], conversation=[];
    var moreFriends = false;
    
    var atHome = $('#home-badge-contact').length;
    
    function loadData(u,a){
        var container;
        $.ajax({
            url: u+'?breakcache='+Math.random(),
            dataType: "json",
            async: a,
            timeout:3000,
            success: function( data ) {
                container = data;
            }
        }); 
        return container;
    }
    
    
    //get the icon of a status
    function getIcon(st){
        var valid = true, s="";
        $.each(status,function(i,v){
            if(v['value'].length){
                if(v['value']===st){
                    s=v['imageSrc'];
                    valid = false;
                }
                
            }
            return valid;
        });
        return s;
    }
    function changeStatus(localStatus){ 
        $('#select-status').ddslick({
            data:localStatus,
            width:57,
            background: "transparent",
            selectText: "Select your status",
            imagePosition:"right",
            onSelected: function(data){
                $.each(data, function(i,v){
                    if(v['value']){
                        $.post("status?status="+v['value']);  
                    }   
                });
            }   
        });
    }
    function createFriendsRequestView(data){
        $( "#view-requests" ).html("");
        $.each(data, function (index, value) {
            var a = $('<a>accept</a>').attr('href','#').attr('class',value['id']);
            var d = $('<a>decline</a>').attr('href','#').attr('class',value['id']);
            a.click(function (){
                answerFriendRequest(value['id'],true);
            });
            d.click(function (){
                answerFriendRequest(value['id'],false);
            });
            var a1 = $('<td></td>').append(a);
            var d1 = $('<td></td>').append(d);
            var x = $("<tr>" + "<td>" + value["username"] + "</td>" + "</tr>").append(a1).append(d1);
            $( "#view-requests" ).append( x);
        });
        var n = data.length;
        $(".nb-friends-req").text(n);
        if($("#home-badge-contact").length){
            $("#home-badge-contact").text(n); 
        }
    }
    
    function changePasswd(){
        var passwd = $("#password"),
        newPasswd = $("#newPasswd"),
        newPasswd2 = $( "#newPasswd2" ),
        allFields = $( [] ).add(passwd).add(newPasswd).add(newPasswd2),
        tips = $( ".validateTips" );
        
        function updateTips( t ) {
            tips
                    .text( t )
                    .addClass( "ui-state-highlight" );
        }
        function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips( "Length of " + n + " must be between " +
                        min + " and " + max + "." );
                return false;
            } else {
                return true;
            }
        }
        function isSame(p1,p2 ) {
            if ( p1.val()!== p2.val() ) {
                p1.addClass( "ui-state-error" );
                updateTips("password are differents");
                p1.val("");p2.val("");
                return false;
            } else {
                return true;
            }
        }
        function checkPassword( o) {
            var uvalid=true;
            $.ajax({
                url: "checkPassword?password="+o.val(),
                dataType: "json",
                async: false,
                success: function( data ) {
                    if(!data["valid"]){
                        o.addClass( "ui-state-error" );
                        updateTips( "wrong password! Please retry");
                        uvalid = false;
                    }
                }
            });
            return uvalid;
        }
        $( "#submit-passwd" ).click(function() {
            var bValid = true;
            allFields.removeClass( "ui-state-error" );
            bValid = bValid && checkLength( passwd, "password", 3, 40 );
            bValid = bValid && checkPassword(passwd);
            bValid = bValid && checkLength( newPasswd, "password", 3, 40 );
            bValid = bValid && checkLength( newPasswd2, "username", 3, 40 );
            bValid = bValid && isSame(newPasswd, newPasswd2);
            
            if ( bValid ) {
                tips.text("");
                //send request to server
                $.ajax({
                    type: 'POST',
                    url: 'changePassword?password='+passwd.val()+'&newPwd='+newPasswd.val()+'&confirm='+newPasswd2.val(),
                    timeout: 3000,
                    success: function(data) {
                        
                        $("#change-password-form").hide();      
                        $('.validateTips').html("<div style='padding-left:15px'><span class='glyphicon glyphicon-ok'></span>"+
                                " Your password has been changed successfuly</div>").addClass('btn-green');
                        setTimeout(function(){
                            $(".validateTips").html("");
                            $("#change-password-form").show();
                            $("#change-password-form * input").val("");
                            $('#close').click();
                        },2000);
                    },
                    error: function() {
                        alert("something went wrong");
                    }
                });    
                
            }
        });
    } 
    
    //respond to friend request
    function answerFriendRequest(id,accept){
        $.post('acceptContact?contact='+id+'&accept='+accept);
    }
    
    
    function updateFriendRequestView(){
        var requests = loadData("getAllContactRequests", false);
        if(requests.length){
            createFriendsRequestView(requests);
        }
        else{
            $( "#view-requests" ).html("");
            $(".nb-friends-req").text(0);
            if(atHome){
                $("#home-badge-contact").text(0); 
            }
        }
    }
    //display the user we are tchatting with
    function updatePanel(index) {
        var datarecord = model.items[index];
        var imgurl = getIcon(datarecord.status);
        $('#remote-status').attr('src',imgurl);
        $('#remote-username').html(datarecord.username);
        /* if(!conversation[index]){
            var m = $("<div></div>");
            conversation[index]={
                username:datarecord.username,
                message:m
            };
        };*/
        $('#message-pane').html(conversation[index].message);
        var badge = $("#"+datarecord.username+"badge");
        badge.text("");
        conversation[index].nbmessage = 0;
        $('#remote-user').show();
        $('#textfield').show();
        
    }
    function displayUserDetails(index){
        var datarecord = model.items[index];
        var username = datarecord.username;
        var location = datarecord.location;
        var admin = datarecord.isAdmin;
        var firstname = datarecord.firstname;
        var lastname = datarecord.lastname;
        var content = $('<div></div>').append("<h1>"+firstname+" "+lastname+"</h1> <br>")
                .append('Pseudo : '+username+"<br>")
                .append('Location : '+location.lenght?localUser:"unknown"+"<br>")
                .append('Administrator'+admin?'yes':'no'+"<br>");
    }
    function initializeConversation(){
        $.each(model.items, function(i, v){
            var message = $("<div></div>").attr('id','message-content');
            conversation.push({username:v.username,message:message,nbmessage:0});
        });
    }
    function positionMessagePane(){
        var contentHeight = $('#message-content').height();
        var containerHeight = $('#message-pane').height();
        var offset = contentHeight - containerHeight+40;
        if(offset>0)
            $('#message-pane').scrollTop(offset+20);
    }
    function displayMessage(username,message){
        var  index = $('#userlist').jqxListBox('selectedIndex');
        var template = $('<div></div>').append(username+' : '+message);
        conversation[index].message.append(template);
        var panel = $('#message-pane');
        panel.html(conversation[index].message);
        positionMessagePane();
    }
    function isFile(str){
        return str.match("^{_file_}");
    }
    function isLink(str){
        return str.match("^{_link_}");
    }
    function handleConversation(){
        //case message
        $('#type-msg').on('keypress', function(e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            //enter key
            if(code === 13) { 
                //var localUsername = localUser.username;
                var typedMessage = $(this).val();
                if($.trim(typedMessage)){
                    //get the selected user (the one we are discussing with)
                    var selectedIndex = $('#userlist').jqxListBox('selectedIndex');
                    displayMessage('me',typedMessage);
                    //post the message to the server
                    $.post('sendTextMessage?message='+typedMessage+'&contact='+model.items[selectedIndex].id);
                    $(this).val("");
                }
            }
        });
        
        //case file
        $('#upload').fileupload({
            done: function (e, data) {
                var selectedIndex = $('#userlist').jqxListBox('selectedIndex');
                var filename = data.files[0].name;
                var id = model.items[selectedIndex].id;
                displayMessage('me',"File sent successfuly : "+filename);
                $.post('sendTextMessage?message={_file_}'+filename+'&contact='+id);
            }
        });
        
        //case link
        $('#link-button').click(function (){
            var selectedIndex = $('#userlist').jqxListBox('selectedIndex');
            var link = $('#link-form').val();
            var id = model.items[selectedIndex].id;
            displayMessage('me',"link sent successfuly : "+link);
            $.post('sendTextMessage?message={_link_}'+link+'&contact='+id);
            $("#link-form").val('http://');
        });
    }
    var received=[];
    function readMessage(){
        received = loadData('receiveNewTextMessages',false);
        if(received.length){
            $.each(received, function(i,v){
                var username = v.from;
                var message = v.message;
                if(isFile(message)){
                    var str = message.substring(8);
                    message = 'New file received  <a target="_blank" href="sendFile?getfile='+
                            str+'"><span class="glyphicon glyphicon-file"></span>'+str+'</a>';
                }
                else if(isLink(message)){
                    var str = message.substring(8);
                    message = 'New link received  <a target="_blank" href="'+
                            str+'"><span class="glyphicon glyphicon-link"></span>'+str+'</a>';
                };
                var index = findIndex(username);
                var selectedIndex = $('#userlist').jqxListBox('selectedIndex');
                /*if the received message is for the user we are currently discussing with
                   display the message 
                 */
                if(!atHome && selectedIndex===index){
                    displayMessage(username, message);
                }
                else{
                    var template = $('<div></div>').append(username+' : '+message);
                    conversation[index].message.append(template);
                    var badge = $("#"+username+"badge");
                    conversation[index].nbmessage++;
                    badge.text(conversation[index].nbmessage);
                }
                
            });
            
        }
        
    }
    //find the index of the user in the userlist
    function findIndex(username){
        var valid = true;
        var index = -1;
        $.each(model.items, function(i,v){
            if(v.username ===username) {
                index = i;
                valid = false;
            }
            return valid;
        });
        return index;
    };
    
    //get the localUser details
    localUser = loadData("getUserDetails",false);
    $("#username-wrapper").text(localUser['username']);
    //display admin tools if the local user is admin
    if(localUser['isAdmin']) $("#admin").removeClass("hidden");
    
    //load all status to get their icon
    status = loadData("allStatus",false);
    localStatus = status.slice();
    localStatus.pop();
    changePasswd();
    changeStatus(localStatus);
    
    var url = "getFriends";
    
    var viewModel = function () {
        this.items = ko.observableArray();
        var me = this;
        var jsonData = loadData('getFriends',false);
        me.items = jsonData.sort(function(obj1, obj2) {
            return obj1.id - obj2.id;
        });
    };
    $('#userlist').on('select', function (event) {
        if(!atHome){
            updatePanel(event.args.index);
        }
    });
    var model = new viewModel();
    function loadFriends(selected){
        
        // prepare the data
        var source =
                {
                    datatype: "observablearray",
            datafields: [
                { name: 'id' },
                { name: 'username' },
                { name: 'location' },
                { name: 'firstname' },
                { name: 'lastname' },
                { name: 'status' }
            ],
            id: 'id',
            localdata: model.items
        };
        var dataAdapter = new $.jqx.dataAdapter(source);
        $('#userlist').jqxListBox({
            source: dataAdapter, width:"100%",height:145, theme:'custom',
            selectedIndex:selected,
            valueMember:'status',
            scrollBarSize: 25,
            renderer: function (index, label, value) {
                initializeConversation();
                var datarecord = model.items[index];
                var imgurl = getIcon(datarecord.status);
                var img = '<img height="15" width="15" src="' + imgurl + '"/>';
                var nb = conversation[index].nbmessage;
                var nbmessage = nb?nb:"";
                var badge = '<span  id="'+datarecord.username+'badge'+'" class="badge" >'+nbmessage+'</span>';
                var table = '<table style="min-width: 120px;"><tr><td style="width: 40px;" rowspan="2">' + img + 
                        '</td><td>' + datarecord.firstname + " " + datarecord.lastname +""+ '</td> <td>' + badge+'</td></tr></table>';
                return table;
            }
        });
        ko.applyBindings(model);
        dataAdapter.dataBind();
    } 
    initializeConversation();
    loadFriends(-1);
    if(!atHome){
        handleConversation();
    }
    
    setInterval(updateFriendRequestView, reloadTime);
    setInterval(function(){
        var selectedIndex = $('#userlist').jqxListBox('selectedIndex');
        /*if(!atHome){
            initializeConversation();
        }*/
        model = new viewModel();
        //$('#userlist').jqxListBox('refresh');
        loadFriends(selectedIndex );
        if(!atHome) readMessage();
    },reloadMessage);
    
    
    /*
     * files ......
     */
    function createWindow() {
        //send file window
        $('#fileUploadWindow').jqxWindow({
            showCollapseButton: true, maxHeight: 400, maxWidth: 700, minHeight: 200, minWidth: 200, 
            height: $("#message-pane").height(), width: 263,
            position:[$("#userlist").width()+20,$("#message-pane").height()-$("#textfield").height()+14],
            title:'Send file'
        });
        //send link window
        $('#linkWindow').jqxWindow({
            showCollapseButton: true, maxHeight: 200, maxWidth: 400, minHeight: 20, minWidth: 200, 
            height: 80, width: 350,
            position:[$("#userlist").width()*2+20,$("#message-pane").height()*1.51],
            title:'Send link'
        });
    };
    if(!atHome) {
        createWindow();
        $('#fileUploadWindow').hide();
        $('#linkWindow').hide();
        $('.send-file').click(function (){
            if($('#userlist').jqxListBox('selectedIndex')!==-1)
                $('#fileUploadWindow').show();
        });
        $('.send-link').click(function (){
            if($('#userlist').jqxListBox('selectedIndex')!==-1)
                $('#linkWindow').show();
        });
    }
    
});